package com.jc.service.yzpService;

import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.HttpUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.mapper.XorderMapper;
import com.jc.ds.model.*;
import com.jc.framework.enums.*;
import com.jc.service.h5.ShopService;
import com.jc.service.jctask.JcTaskService;
import com.jc.service.model.yzp.YzpOrderAddress;
import com.jc.service.order.XorderService;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@SuppressWarnings("all")
@Service
public class YZPOrderServiceImpl implements YZPOrderService {

    //分销商品密钥
    private final String appSercret = "c97120ac-3f2d-48e2-b8a7-65acf639d342";

    @Value("${yzp.url}")
    private String url;
    @Autowired
    private XorderService xorderService;
    @Autowired
    private XorderMargeService xorderMargeService;
    @Autowired
    private XorderProcessService xorderProcessService;
    @Autowired
    private SystemLogListService systemLogListService;
    @Autowired
    private JcTaskService jcTaskService;
    @Autowired
    private XorderproductsService xorderproductsService;
    @Autowired
    private SupplierGoodsService supplierGoodsService;
    @Autowired
    private SupplierProductService supplierProductService;
    @Autowired
    private ShopService shopService;


    //分销商品下订单
    @Override
    public Map<String, Object> xOrder(CustomXorder order) {

        YzpOrderAddress yzpOrderAddress = packYzpOrderAddress(order);

        String result = null;
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("appSecret", yzpOrderAddress.getAppSecret());
        orderMap.put("pCodeAndAmount", yzpOrderAddress.getpCodeAndAmount());
        orderMap.put("phone", yzpOrderAddress.getPhone());
        orderMap.put("parentAddr", yzpOrderAddress.getParentAddr());
        orderMap.put("detailAddr", yzpOrderAddress.getDetailAddr());
        orderMap.put("name", yzpOrderAddress.getName());
        orderMap.put("orderCode", yzpOrderAddress.getOrderCode());

        try {
//            result = HttpUtil.post("http://api.youzhipai.cn/api/addOrder", orderMap);
            result = HttpUtil.post(url + YzpApi.PRODUCT_ORDER_SUPPLIER.getName(), orderMap);
            Map<String, Object> backMap = JSONObject.parseObject(result);
            if (!backMap.get("msg").equals("下单成功")) {
                throw new BaseServiceException("推送订单失败,原因:" + JSONObject.parseObject(result, Map.class).get("msg"));
            }
            XorderProcess xorderProcess = new XorderProcess();
            xorderProcess.setChannelOrderId(order.getChannelOrderId());
            xorderProcess.setDetailDesc("分销商品推送订单成功");
            xorderProcess.setProcessCreate(new Date());
            xorderProcess.setOrderId(order.getId());
            xorderProcess.setOptionUserName("系统定时");
            xorderProcessService.add(xorderProcess, false);
            systemLogListService.addSystemLog(JSONObject.toJSONString(orderMap), Conclusion.OK, null, LogType.YZP_PUSH_ORDER, result);

            Xorder xorderUpdate = new Xorder();
            xorderUpdate.setId(order.getId());
            xorderUpdate.setSupplierOrderNo(null);
            xorderUpdate.setOrderStatus(OrderStatus.push_ok.getDesc());
            xorderService.modify(xorderUpdate, false);


            //推送成功创建定时任务
            jcTaskService.addTask(TaskType.push_express, order.getpId().toString(), JSONObject.toJSONString(orderMap), Booleans.FALSE, null);


        } catch (Exception e) {
            XorderProcess xorderProcess = new XorderProcess();
            xorderProcess.setChannelOrderId(order.getChannelOrderId());
            xorderProcess.setDetailDesc("分销商品推送订单失败");
            xorderProcess.setProcessCreate(new Date());
            xorderProcess.setOrderId(order.getId());
            xorderProcess.setOptionUserName("系统定时");
            xorderProcessService.add(xorderProcess, false);
            systemLogListService.addSystemLog(JSONObject.toJSONString(orderMap), Conclusion.FAIL, null, LogType.YZP_PUSH_ORDER, result);

            Xorder xorderUpdate = new Xorder();
            xorderUpdate.setId(order.getId());
            xorderUpdate.setSupplierOrderNo(null);
            xorderUpdate.setOrderStatus(OrderStatus.push_final.getDesc());
            xorderService.modify(xorderUpdate, false);
            //推送失败创建定时任务
            jcTaskService.addTask(TaskType.push_express, order.getpId().toString(), JSONObject.toJSONString(orderMap), Booleans.FALSE, null);
            e.printStackTrace();
        }
        return resultMap;
    }


    //封装订单信息
    private YzpOrderAddress packYzpOrderAddress(CustomXorder order) {
        YzpOrderAddress orderAddress = new YzpOrderAddress();
        //下单人名字
        orderAddress.setName(order.getConsigneeName());
        //详细地址
        orderAddress.setDetailAddr(order.getConsigneeAddress());
        //第三方分销订单号
        orderAddress.setOrderCode(order.getChannelOrderId());
        //收货人手机号
        orderAddress.setPhone(order.getConsigneeMobile());
        //密钥
        orderAddress.setAppSecret(appSercret);

        String consigneeProvince = order.getConsigneeProvince();//省
        String consigneeCityName = order.getConsigneeCityName();//市
        String consigneeRegionName = order.getConsigneeRegionName();//qu

        //分销商品拼接地址parentAddr
        StringBuilder sb = new StringBuilder();
        sb.append(order.getConsigneeProvinceName());
        if (consigneeCityName != null) {
            sb.append("-").append(order.getConsigneeCityName());
        }
        if (consigneeRegionName != null) {
            sb.append("-").append(order.getConsigneeRegionName());
        }
        String parentAddr = sb.toString();
        // 省市区，下划线分开
        orderAddress.setParentAddr(parentAddr);

        Long id = order.getId();
        String supplierId = order.getSupplierId();//供应商id
//        OrderProducts orderProducts = this.xorderproducts.queryXorderProducts(id);
//        String productName = orderProducts.getProductName();
        OrderProducts orderProducts = new OrderProducts();
        orderProducts.setOrderId(id);
        List<OrderProducts> orderProductsQuers = this.xorderproductsService.queryXorderProducts(orderProducts);
        for (OrderProducts orderProductsQuer : orderProductsQuers) {
            SupplierProduct supplierProduct = new SupplierProduct();

            supplierProduct.setProductId(orderProductsQuer.getSupplierProductId());
            List<SupplierProduct> supplierProducts = this.supplierProductService.queryAll(supplierProduct);
            String goodsId = null;
            for (SupplierProduct product : supplierProducts) {
                goodsId = product.getGoodsId();//供应商的商品编码
            }


            Integer productNums = orderProductsQuer.getProductNums();//订单的商品数量
            StringBuilder stringBuilder = new StringBuilder();
            String s = stringBuilder.append(goodsId).append("_").append(productNums).toString();

            orderAddress.setpCodeAndAmount(s);//分销商品的商品编码和数量 字段
        }
        return orderAddress;
    }

    /**
     * 分销商品 获得物流和订单
     */

    @Override
    public Map<String, Object> getLogistics(Map<String, Object> param) {


        Object appSecret = param.get("appSecret");

        Map<String, Object> resultMap = new HashMap<>();
        ArrayList<Xorder> orderList = new ArrayList<>();

        param.put("appSecret", appSercret);
        if (param == null) {
            resultMap.put("status", "fail");
            resultMap.put("code", "999");
            resultMap.put("code", "参数为空");
            return resultMap;
        }
        String result = null;
        try {
            result = HttpUtil.get(url + YzpApi.PRODUCT_Logistics.getName(), param);
//            result = "{\"status\":\"success\",\"code\":200,\"data\":[{\"childOrderCode\":\"我方订单号\",\"orderCode\":201812271883,\"shipWay\":\"快递公司名称\",\"shipWayPinyin\":\"快递公司拼音\",\"shipNumber\":\"快递单号\"}]}";

        } catch (Exception e) {
            e.printStackTrace();
        }



                    /* {"status":"success","code":200,
            "data":[{
            "childOrderCode":”我方订单号”
            "orderCode":"你方订单号"
            "shipWay":"快递公司名称"
            "shipWayPinyin":"快递公司拼音",
            "shipNumber":”快递单号”
            },{
            "childOrderCode":”我方订单号”
            "orderCode":"你方订单号"
            "shipWay":"快递公司名称"
            "shipWayPinyin":"快递公司拼音",
            "shipNumber":”快递单号”
            }]}
        * */
        Map<String, Object> map = JSONObject.parseObject(result);
        if (map.get("data") == null) {
            resultMap.put("status", "fail");
            resultMap.put("code", "888");
            resultMap.put("code", "data数据为空");
            return resultMap;
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) map.get("data");
        for (Map<String, Object> datum : data) {
            Object childOrderCode = datum.get("childOrderCode");
            Object orderCode = datum.get("orderCode");
            Object shipWay = datum.get("shipWay");
            Object shipWayPinyin = datum.get("shipWayPinyin");
            Object shipNumber = datum.get("shipNumber");


            //对比子订单 orderMarge
            XorderMarge xorderMarge = new XorderMarge();
            xorderMarge.setChannelOrderId(String.valueOf(orderCode));
            List<XorderMarge> xorderMarges = this.xorderMargeService.queryAll(xorderMarge);
            if (CollectionUtils.isEmpty(xorderMarges)) {//无合单记录
                Xorder xorder1 = new Xorder();
                xorder1.setChannelOrderId(String.valueOf(orderCode));
                List<Xorder> xorders = this.xorderService.queryAll(xorder1);
                if (CollectionUtils.isEmpty(xorders)) {
                    resultMap.put("msg", "订单不存在，无法出库");
                    resultMap.put("code", "777");
                    return resultMap;
                }
                if (xorders.size() > 1) {
                    resultMap.put("msg", "订单记录存在多条,无法出库");
                    resultMap.put("code", "999");
                    return resultMap;
                } else {

                    Xorder xorder = new Xorder();


                    xorder.setSupplierOrderNo(String.valueOf(childOrderCode));
                    xorder.setExpressNo(String.valueOf(shipNumber));//返回的快递单
                    xorder.setExpressName(String.valueOf(shipWay));
                    xorder.setChannelOrderId(String.valueOf(orderCode));
                    xorder.setOrderStatus(OrderStatus.outstorage.getName());
                    xorder.setUpdateTime(new Date());
                    for (Xorder xorder2 : xorders) {
                        xorder.setId(xorder2.getId());

                        int modify = this.xorderService.modify(xorder, false);
                        this.xorderProcessService.addXorderProcess(xorder2.getChannelOrderId(), OrderStatus.outstorage.getName(), "分销商品物流查询", xorder2.getId());

                        //订单日志记录表
                        //推送商城
                        String s = this.shopService.pushOrder(String.valueOf(xorder2.getChannelOrderId()));

                        if ("1".equals(s)) {
                            throw new BaseServiceException("推送订单号失败" + xorder2.getId());
                        } else {
                            resultMap.put("code", "okokok");
                            return resultMap;
                        }

                    }


                }
            } else {
                //存在合单记录
                for (XorderMarge marge : xorderMarges) {
                    String channelOrderId = marge.getChannelOrderId();
                    Xorder xorder1 = this.xorderService.queryById(Long.valueOf(channelOrderId));
                    orderList.add(xorder1);
                    for (Xorder xorder2 : orderList) {
                        xorder2.setSupplierOrderNo(String.valueOf(childOrderCode));
                        xorder2.setExpressNo(String.valueOf(shipNumber));//返回的快递单
                        xorder2.setExpressName(String.valueOf(shipWay));
                        xorder2.setChannelOrderId(String.valueOf(orderCode));
                        xorder2.setOrderStatus(OrderStatus.outstorage.getName());
                        xorder2.setUpdateTime(new Date());
                        this.xorderService.modify(xorder2, false);
                        this.xorderProcessService.addXorderProcess(xorder2.getChannelOrderId(), OrderStatus.outstorage.getName(), "分销商品物流查询", xorder2.getId());

                        //订单日志记录表
                        //推送商城
                        String s = this.shopService.pushOrder(String.valueOf(xorder2.getChannelOrderId()));
//                    String s = this.shopService.pushOrder("201812271820");
                        if ("1".equals(s)) {
                            this.xorderProcessService.addXorderProcess(xorder2.getChannelOrderId(), OrderStatus.push_final.getName(), "分销商品物流查询", xorder2.getId());

                            throw new BaseServiceException("推送订单号失败" + xorder2.getId());
                        } else {
                            resultMap.put("code", "okokok");
                            this.xorderProcessService.addXorderProcess(xorder2.getChannelOrderId(), OrderStatus.outstorage.getName(), "分销商品物流查询", xorder2.getId());
                            return resultMap;
                        }
                    }
                }
            }
        }
        return resultMap;
    }


    @Autowired
    private XorderMapper xorderMapper;

    /**
     * 更改状态退货中
     */

    @Override
    public Map<String, Object> clickTuiHuo(Map<String, Object> params) {

        Map<String, Object> result = new HashMap<>();

        String id = (String) params.get("id");
        if (!"null".equals(id) && id != null && !"".equals(id)) {
            Xorder xorder = new Xorder();
            xorder.setId(Long.valueOf(id));
            List<Xorder> xorders = this.xorderMapper.selectAll(xorder);
            int i = 0;
            for (Xorder xorder1 : xorders) {

                Xorder xorder2 = new Xorder();
                xorder2.setId(xorder1.getId());
                xorder2.setChannelOrderId(xorder1.getChannelOrderId());
                xorder2.setOrderStatus(OrderStatus.tuiHuoIng.getName());


                i = this.xorderService.modify(xorder2, false);

            }
            if (i == 1) {
                result.put("msg", "请求成功， 状态为退货中~");
            }
        }

        return result;
    }
}
